import PySimpleGUI as sg
from MainLayout import Main_layout
from Window.print_window import _print_window, write_to_excel
from loguru import logger


class Excel_generate():
    def __init__(self):
        # 改变主题
        sg.ChangeLookAndFeel('Default1')
        # 配置主页面
        title = [
            [sg.Text('坦克智能出入库管理系统', size=(38, 1), justification='center', font=("Helvetica", 16),
                     k='-TEXT HEADING-')]]
        title += Main_layout
        self.window = sg.Window('坦克智能出入库管理系统', title, finalize=True, grab_anywhere=False, alpha_channel=1)
        logger.add('print.log')

    def circle_event(self):
        # 启动打印窗口标识符
        biaoqian_layout_active = False
        while True:
            # 循环读取窗口信息，事件和值
            self.event, self.values = self.window.read(timeout=1000)

            # 如果触发关闭事件就关闭窗口
            if self.event in (sg.WIN_CLOSED, 'Exit'):
                break

            # 如果点击这个按钮就弹出这个标签打印窗口
            elif self.event == "-biaoqian-" and not biaoqian_layout_active:
                biaoqian_window = _print_window()
                biaoqian_layout_active=True
            elif biaoqian_layout_active:
                biaoqian_event, biaoqian_values = biaoqian_window.read(timeout=1000)
                # 如果触发了关闭窗口时间
                if biaoqian_event in (sg.WIN_CLOSED, 'Exit'):
                    biaoqian_layout_active = False
                    biaoqian_window.close()
                # 更新事件，更新excel文件
                elif biaoqian_event == '-update-':
                    try:
                        if not (str(biaoqian_values['month_combo']).isdigit() and str(
                                biaoqian_values['Q-input']).isdigit() and str(
                                biaoqian_values['number_combo']).isdigit()):
                            sg.popup_error('三个参数需输入数字！！！')
                        elif (biaoqian_values['-file_path-'] == ''):
                            sg.popup_error('请选择一个excel文件！')
                        else:
                            label_data = write_to_excel(biaoqian_values)
                            sg.popup_quick_message('成功修改excel！')
                            logger.info('打印数量为{}-最后打印的标签是{}'.format(biaoqian_values['number_combo'],label_data))
                    # 这个捕获的是当excel打开的时候无法操作的错误
                    except PermissionError:
                        sg.popup_error('请关闭excel表格再进行操作！')

        self.window.close()


if __name__ == '__main__':
    E = Excel_generate()
    E.circle_event()
